package app.nbdevices.utils;

import app.nbdevices.modle.appModle.RegisterModle;
import app.nbdevices.modle.appModle.TaskDetailModle;
import app.nbdevices.modle.appModle.TaskOutputModle;
import app.nbdevices.modle.appModle.TaskResModle;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RegisterUtil {

    public static TaskResModle regRequest( List<RegisterModle> infoList,int pid,String taskName,HttpsUtil httpsUtil) throws Exception {
        httpsUtil.initSSLConfigForTwoWay();
        String accessToken=login(httpsUtil);
        String fileId=upRegFile(infoList,pid,httpsUtil,accessToken);
        String taskId=exuRegTask(fileId,taskName,accessToken,httpsUtil);
        System.out.println(taskId);
      //  taskId.substring(taskId.indexOf(':')-1,);
        System.out.println("taskId:"+taskId.substring(taskId.indexOf(":")+2,taskId.lastIndexOf("\"")));
        String res=checkChildTask(taskId.substring(taskId.indexOf(":")+2,taskId.lastIndexOf("\"")),accessToken,httpsUtil,infoList.size());
        JSONObject root = new JSONObject().parseObject(res);
        System.out.println("root:"+root);
        TaskResModle taskResModle = root.toJavaObject(TaskResModle.class);
        return taskResModle;
    }
    public static String checkChildTask(String taskId,String accessToken,HttpsUtil httpsUtil,Integer time) throws Exception{
        Thread.sleep(1000l+time*200l);
        String usr="https://device.api.ct10649.com:8743/iocm/app/batchtask/v1.1.0/taskDetails?appId=brlQSSfCWBnhv0NVXIaWqvWwD1EataskId=0&taskId=ddd";
        String url=Constant.BASE_URL+"/iocm/app/batchtask/v1.1.0/taskDetails?appId=brlQSSfCWBnhv0NVXIaWqvWwD1Ea&taskId="+taskId+"&pageSize=250";

        System.out.println(url);
                System.out.println(usr);
                String appid=Constant.APPID;
                System.out.println(url);
                System.out.println(url);
                Map<String, String> header = new HashMap<>();
                header.put(Constant.HEADER_APP_KEY, appid);
                header.put(Constant.HEADER_APP_AUTH, "Bearer" + " " + accessToken);

                Map<String,String> params=new HashMap<>(1);

                StreamClosedHttpResponse responseRegisterDirectConnectedDevice = httpsUtil.doGetWithParasGetStatusLine(url, params, header);

                System.out.println(responseRegisterDirectConnectedDevice.getContent());
                return responseRegisterDirectConnectedDevice.getContent();

        }
        public static String exuRegTask(String fileId,String taskName,String accessToken,HttpsUtil httpsUtil) throws Exception {
            String appid=Constant.APPID;

            //Please make sure that the following parameter values have been modified in the Constant file.
            String url=Constant.BASE_URL+"/iocm/app/batchtask/v1.1.0/tasks";

            Map<String, String> header = new HashMap<>();
            header.put(Constant.HEADER_APP_KEY, appid);
            header.put(Constant.HEADER_APP_AUTH, "Bearer" + " " + accessToken);

            //上传文件后返回的文件ID
            // String fileId="bb3dc048-57fa-4b5f-ac7c-1047ec46c64b";
            Map<String,Object> param=new HashMap<>(10);
            param.put("fileId",fileId);

            //   String taskName="oneTest04";
            //指定批量注册任务
            String taskType="DeviceReg";
            //设置任务执行超时
            int timeout=30;

            Map<String, Object> Body = new HashMap<>();
            Body.put("app_key",appid);
            Body.put("Authorization",accessToken);
            Body.put("appId",appid);
            Body.put("param",param);
            Body.put("taskName",taskName);
            Body.put("taskType",taskType);
            Body.put("timeout",timeout);
            String jsonRequest = JsonUtil.jsonObj2Sting(Body);

            StreamClosedHttpResponse responseRegisterDirectConnectedDevice = httpsUtil.doPostJsonGetStatusLine(url, header, jsonRequest);
//
//        System.out.println("RegisterDirectConnectedDevice, response content:");
//        System.out.println(responseRegisterDirectConnectedDevice.getStatusLine());
//        System.out.println(responseRegisterDirectConnectedDevice.getContent());

            String jsonstring=responseRegisterDirectConnectedDevice.getContent();
            String res=JsonUtil.convertJsonStringToObject(jsonstring,Object.class).toString();
            return jsonstring;
        }
        public static String upRegFile(List<RegisterModle> infoList,int pid,HttpsUtil httpsUtil,String accessToken) throws Exception {

            String productId=null;
            switch(pid){
                case 1:productId=Constant.DOOR;
                    break;
                case 2:productId=Constant.YANGAN;
                    break;
                case 3:productId=Constant.WATER;
                    break;
                case 4:productId=Constant.ELE;
                break;
            default:productId="error";
        }
      //  productId= "aba5469fc03fc04f49d33318005f1a30";
        String url=Constant.BASE_URL+"/iocm/app/batchtask/v1.1.0/deviceRegFiles?appId="+Constant.APPID;
        StringBuffer contents=new StringBuffer();
        contents.append("nodeId,productId,psk,isSecure,verifyCode,timeout,name,region,location,latitude,longitude,address,timezone,groupId,tags,customField,imsi");
        for(RegisterModle info:infoList){
            contents.append("\r\n"+info.getNodeId()+","+productId);
        }
        System.out.println(contents);
        String fileName="regInfo.xls";
        Map<String, Object> Body = new HashMap<>();
        Body.put("fileName",fileName);
        Body.put("fileContent",contents.toString());
        String jsonRequest = JsonUtil.jsonObj2Sting(Body);


        Map<String, String> header = new HashMap<>();
        header.put(Constant.HEADER_APP_KEY, Constant.APPID);
        header.put(Constant.HEADER_APP_AUTH, "Bearer" + " " + accessToken);

        StreamClosedHttpResponse responseRegisterDirectConnectedDevice = httpsUtil.doPostJsonGetStatusLine(url, header, jsonRequest);

        String jsonstring=responseRegisterDirectConnectedDevice.getContent();
        String res=JsonUtil.convertJsonStringToObject(jsonstring,Object.class).toString();
        // System.out.println(res.substring(res.indexOf("=")+1,res.length()-1));
        return res.substring(res.indexOf("=")+1,res.length()-1);
    }
    public static List<RegisterModle> Xls2PojoList(MultipartFile mFile) throws IOException {
        InputStream iFile=mFile.getInputStream();
        Workbook wb = new HSSFWorkbook(iFile);
        Sheet sheet = wb.getSheetAt(0);
        int rowNum=sheet.getPhysicalNumberOfRows()-2;

        List<RegisterModle> arr=new ArrayList<>(rowNum);
        for(int i=1;i<=rowNum;i++){
            RegisterModle r=new RegisterModle();
            r.setNodeId(sheet.getRow(i).getCell(0).toString());
            r.setAddrId(sheet.getRow(i).getCell(1).toString());
            r.setName(sheet.getRow(i).getCell(2).toString());
            arr.add(r);
            System.out.println(r);
        }
        return arr;
    }

    public static void main(String[] args) throws Exception {

        byte[] decode = ConvertUtil.getBase64Codec().decode("hoaBBGYRIiA=");
        for(byte d:decode){
            System.out.println(Integer.toHexString(d&0xff));
        }
//        String taskId="5e900ed25edd3b6664868e82";
//        HttpsUtil httpsUtil=new HttpsUtil();
//        httpsUtil.initSSLConfigForTwoWay();
//        checkChildTask(taskId,login(httpsUtil),httpsUtil,1);
//        FileInputStream iFile=
//                new FileInputStream(new File("E:/270menji1643-1900.xls"));
//        Workbook wb = new HSSFWorkbook(iFile);
//        Sheet sheet = wb.getSheetAt(0);
//        int rowNum=sheet.getLastRowNum();
//        System.out.println(rowNum);
//        List<RegisterModle> arr=new ArrayList<>(rowNum);
//        int count=0;
//        for(int i=1;i<rowNum;i++){
//            RegisterModle r=new RegisterModle();
//            r.setNodeId(sheet.getRow(i).getCell(0).toString());
//            r.setAddrId(sheet.getRow(i).getCell(1).toString());
//            r.setName(sheet.getRow(i).getCell(2).toString());
//            System.out.println(r);
//            System.out.println(rowNum);
//            count++;
//            arr.add(r);
//        }
//        int count1=0;
//        for(int i=1;i<3;i++){
//            count1++;
//        }
//        System.out.println("count"+count+"couint1"+count1);
//        String accessToken=login(httpsUtil);
//        String fileId=upRegFile(arr,2,httpsUtil,accessToken);
//        String taskId=exuRegTask(fileId,"dcvvd",accessToken,httpsUtil);
//        String res=checkChildTask(taskId.substring(taskId.indexOf(":")+2,taskId.lastIndexOf("\"")),accessToken,httpsUtil);
//        JSONObject root = new JSONObject().parseObject(res);
//        System.out.println(root);
//        TaskResModle taskResModle = root.toJavaObject(TaskResModle.class);
//        System.out.println(taskResModle);
//        String taskId="{\"taskID\":\"5e5de87de77cc01287c14332\"}";
//        String res=checkChildTask(taskId.substring(taskId.indexOf(":")+2,taskId.lastIndexOf("\"")),"f732d5312b297baead19b57d435fb37",httpsUtil);
//        JSONObject root = new JSONObject().parseObject(res);
//        System.out.println(root);
//        System.out.println(p.substring(p.indexOf(":")+2,p.lastIndexOf("\"")));
//        FileInputStream f=new FileInputStream(new File("E:\\resModle2.xls"));
//        Workbook wb = new HSSFWorkbook(f);
//        Sheet sheet = wb.getSheetAt(0);
//        int rowNum=sheet.getLastRowNum();
//        List<RegisterModle> arr=new ArrayList<>(rowNum);
//        for(int i=1;i<=rowNum;i++){
//            RegisterModle r=new RegisterModle();
//            r.setNodeId(sheet.getRow(i).getCell(0).toString());
//            r.setAddrId(sheet.getRow(i).getCell(1).toString());
//            r.setName(sheet.getRow(i).getCell(2).toString());
//            arr.add(r);
//            System.out.println(r);
//        }

////        String info=upRegFile(arr,1,httpsUtil,"6760715ab25cf0878636c8d8728f");
////        System.out.println(info);
////        String taskId=exuRegTask("68fb64ec-11da-4833-aa19-927e511fbdb4","suiji2","6760715ab25cf0878636c8d8728f",httpsUtil);
////            System.out.println(taskId);
 //  String s= checkChildTask("5e5de660cc1cc60f94b38b7a","f84b2adf325455a073c95c8f75281b6",httpsUtil);
//   String p="{\"totalCount\":6,\"pageNo\":0,\"pageSize\":25,\"taskDetails\":[{\"status\":\"Success\",\"output\":\"{\\\"deviceId\\\":\\\"b6829e95-e1fd-4610-aee4-dfd61f820b50\\\",\\\"timeout\\\":1209600}\",\"error\":null,\"param\":{\"index\":0,\"nodeId\":\"255455123\"}},{\"status\":\"Success\",\"output\":\"{\\\"deviceId\\\":\\\"abe51cb6-14a0-495c-8e6f-06e0ca8b945f\\\",\\\"timeout\\\":1209600}\",\"error\":null,\"param\":{\"index\":1,\"nodeId\":\"457756\"}},{\"status\":\"Success\",\"output\":\"{\\\"deviceId\\\":\\\"f406f0c0-a556-4f24-bdb2-8931816dcfa9\\\",\\\"timeout\\\":1209600}\",\"error\":null,\"param\":{\"index\":2,\"nodeId\":\"789124\"}},{\"status\":\"Fail\",\"output\":null,\"error\":\"{\\\"error_code\\\":100426,\\\"error_desc\\\":\\\"The nodeId is duplicated.\\\"}\",\"param\":{\"index\":3,\"nodeId\":\"147.0\"}},{\"status\":\"Fail\",\"output\":null,\"error\":\"{\\\"error_code\\\":100426,\\\"error_desc\\\":\\\"The nodeId is duplicated.\\\"}\",\"param\":{\"index\":4,\"nodeId\":\"258.0\"}},{\"status\":\"Success\",\"output\":\"{\\\"deviceId\\\":\\\"7e0e9614-b5d7-4803-81cc-c3cc9152890a\\\",\\\"timeout\\\":1209600}\",\"error\":null,\"param\":{\"index\":5,\"nodeId\":\"2354861.0\"}}]}";
     //   String t="{\"totalCount\":6,\"pageNo\":0,\"pageSize\":25,\"taskDetails\":[{\"status\":\"Success\",\"error\":null,\"output\":{\"deviceId\":\"f406f0c0-a556-4f24-bdb2-8931816dcfa9\",\"timeout\":1209600},\"param\":{\"index\":2,\"nodeId\":\"789124\"}},{\"status\":\"Fail\",\"output\":null,\"error\":{\"error_code\":100426,\"error_desc\":\"The nodeId is duplicated.\"},\"param\":{\"index\":3,\"nodeId\":\"147.0\"}},{\"status\":\"Fail\",\"output\":null,\"error\":{\"error_code\":100426,\"error_desc\":\"The nodeId is duplicated.\"},\"param\":{\"index\":4,\"nodeId\":\"258.0\"}}]}";
     //   JSONObject root = new JSONObject().parseObject(s);
//        System.out.println(root);
     //   TaskResModle taskResModle = root.toJavaObject(TaskResModle.class);
//        for(TaskDetailModle td:taskResModle.getTaskDetails()){
//            JSONObject r=new JSONObject().parseObject(td.getOutput());
//            System.out.println(r.toJavaObject(TaskOutputModle.class));
//        }
//
        //  TaskResModle tp=(TaskRes
        //  Modle)JsonUtil.convertJsonStringToObject(t, TaskResModle.class);
      //  System.out.println(taskResModle);
}
    public static String login(HttpsUtil httpsUtil) throws Exception {

        String appId = Constant.APPID;
        String secret = Constant.SECRET;
        String urlLogin = Constant.APP_AUTH;

        Map<String, String> paramLogin = new HashMap<>();
        paramLogin.put("appId", appId);
        paramLogin.put("secret", secret);

        StreamClosedHttpResponse responseLogin = httpsUtil.doPostFormUrlEncodedGetStatusLine(urlLogin, paramLogin);

        System.out.println("app auth success,return accessToken:");
        System.out.println(responseLogin.getStatusLine());
        System.out.println(responseLogin.getContent());
        System.out.println();

        Map<String, String> data = new HashMap<>();
        data = JsonUtil.jsonString2SimpleObj(responseLogin.getContent(), data.getClass());
        return data.get("accessToken");
    }
}
